package secondStage.part5.多线程.线程安全;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: [SellTicket4]
 * @Description:
 * @Author: [黄劲松]
 * @CreateDate: [2021-04-05]
 * @Version: [v1.0]
 */
/*
Lock中提供了获得锁和释放锁的方法
    void lock(): 获得锁
    void unlock(): 释放锁
Lock是接口不能直接实例化，这里采用它的实现类Reentrantlock来实例化
    ReentrantLock (): 创建一个Reentrantlock的实例 .
 */
public class SellTicket4 implements Runnable {
    private int tickets = 100;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();//获得锁
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在售票第" + tickets + "张票");
                    tickets--;
                }
            } finally {
                lock.unlock();//释放锁
            }
        }
    }
}
